package com.wanxi.config;

import com.alibaba.fastjson.JSONObject;
import com.wanxi.dto.ResultDto;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class MyFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
//        判断是否已经登录
//        如果已经登录则放行，否则进入登录页面或者直接返回一个json数据
        req.setCharacterEncoding("utf-8");
        res.setCharacterEncoding("utf-8");
        if (!req.getServletPath().startsWith("/back/")) {
            chain.doFilter(req, res);
            return;
        }
        Object username = req.getSession().getAttribute("username");
        if (username != null) {
            chain.doFilter(req, res);
            return;
        }
//        res.sendRedirect("/html/login.html");
        res.getWriter().println(JSONObject.toJSONString(ResultDto.getInstance("你没有登录")));
    }
}
